using AutoMapper;
using BackData;
using Domain.DTOs.Warehouse;
using Domain.Warehousies;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.Warehouse.laneway;

namespace Team.API.Applocation.Hanldler.Warehouse.laneway
{
    /// <summary>
    /// 查询巷道列表命令处理器
    /// </summary>
    public class GetLanewayListHandler : IRequestHandler<GetLanewayListCommand, APIResult<List<LanewayDTO>>>
    {
        private readonly IMapper _mapper;
        private readonly IRepository<Lanewaymodel> _lanewayRep;
        private readonly IRepository<Warehousemodel> _warehouseRep;
        private readonly ILogger<GetLanewayListHandler> _logger;

        public GetLanewayListHandler(
            IMapper mapper,
            IRepository<Lanewaymodel> lanewayRep,
            IRepository<Warehousemodel> warehouseRep,
            ILogger<GetLanewayListHandler> logger)
        {
            _mapper = mapper;
            _lanewayRep = lanewayRep;
            _warehouseRep = warehouseRep;
            _logger = logger;
        }

        public async Task<APIResult<List<LanewayDTO>>> Handle(GetLanewayListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有未删除的巷道
                var query = _lanewayRep.GetAll().Where(x => !x.IsDel);

                // 按仓库ID筛选
                if (request.Warehouseid.HasValue)
                {
                    query = query.Where(x => x.Warehouseid == request.Warehouseid.Value);
                }

                // 按状态筛选
                if (request.Lanewaystate.HasValue)
                {
                    query = query.Where(x => (int)x.Lanewaystate == request.Lanewaystate.Value);
                }

                // 按名称模糊查询
                if (!string.IsNullOrEmpty(request.Lanewayname))
                {
                    query = query.Where(x => x.Lanewayname.Contains(request.Lanewayname));
                }

                var list = await query.OrderBy(x => x.Id).ToListAsync();

                // 获取所有相关仓库信息
                var warehouseIds = list.Select(x => x.Warehouseid).Distinct().ToList();
                var warehouses = await _warehouseRep.GetAll()
                    .Where(x => warehouseIds.Contains(x.Id) && !x.IsDel)
                    .ToListAsync();

                var warehouseDict = warehouses.ToDictionary(x => x.Id, x => x.Warehousename);

                // 映射为DTO
                var resultDTOs = list.Select(laneway =>
                {
                    var dto = _mapper.Map<LanewayDTO>(laneway);
                    dto.Warehousename = warehouseDict.ContainsKey(laneway.Warehouseid)
                        ? warehouseDict[laneway.Warehouseid]
                        : "未知仓库";
                    dto.LanewaystateText = GetLanewaystateText((int)laneway.Lanewaystate);
                    return dto;
                }).ToList();

                _logger.LogInformation($"查询到 {resultDTOs.Count} 条巷道记录");

                return new APIResult<List<LanewayDTO>>
                {
                    Code = StateCode.OK,
                    Message = "巷道查询成功",
                    Result = resultDTOs
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "巷道查询失败");
                return new APIResult<List<LanewayDTO>>
                {
                    Code = StateCode.Fail,
                    Message = $"巷道查询失败: {ex.Message}",
                    Result = new List<LanewayDTO>()
                };
            }
        }

        private string GetLanewaystateText(int state)
        {
            return state switch
            {
                0 => "空闲中",
                1 => "被占用",
                2 => "维护中",
                _ => "未知状态"
            };
        }
    }
}
